<?php
/**
 * bs多规格sku商城系统
 * ============================================================================
 * 版权所有 2024-2099 wltx666.com，并保留所有权利。
 * 网站地址: https://wltx666.com
 * ============================================================================
 * Author: 草上飞
 * Email: wltx@alipay168.cn
 * QQ: 2719875001
 * Date: 2025/04/03
 * 描述:
 */

namespace app\result\auto;

use app\model\admin\Admin;
use app\model\admin\AdminMenu;
use app\model\auto\Role;
use app\model\auto\RoleAuths;
use app\result\BaseResult;


class RoleResult extends BaseResult
{
    public function __construct()
    {
        parent::__construct();
        $this->model = new Role();
    }

    public function save_data($args): array
    {
        $id = intval($args['id'] ?? 0);
        if ($id) {
            $data = $this->model->data_get(['role_id' => $id]);
            if (!$data) {
                return $this->error_return('数据不存在');
            }
        }
        if ($id) {
            $this->model->data_update(['role_id' => $id], $args);
        } else {
            unset($args['role_id']);
            $this->model->data_add($args);
        }
        return $this->success_return('保存成功');
    }

    // 表格列
    public function el_table_column(): array
    {
        return [
            ['prop' => 'role_id', 'type' => 'text', 'label' => '角色ID', 'minWidth' => '120', 'align' => 'center',],
            ['prop' => 'role_name', 'type' => 'text', 'label' => '角色名称', 'minWidth' => '120', 'align' => 'center',],
        ];
    }

    //列表搜索字段
    private function _searchField(): array
    {
        return [
            ['name' => 'role_name', 'label' => '角色名称', 'type' => 'input', 'placeholder' => '角色名称',],
        ];
    }

    // 获取公共条件限制
    private function _where($args = []): array
    {
        $where = [];
        $keyword = trim($args['role_name'] ?? '');
        $status = $args['status'] ?? '';
        if ($keyword) {
            $where[] = ['role_name', 'like', '%' . trim($args['keyword']) . '%'];//todo 自己改成对应的字段
        }

        if ($status) {
            $where[] = ['status', '=', $status];
        }
        return $where;
    }

    public function list($args = []): array
    {
        $page = intval($args['page'] ?? 1);
        $pageSize = intval($args['limit'] ?? 10);
        $sort_by = trim($args['sort_by'] ?? 'role_id desc');
        $where = $this->_where($args);
        $total = $this->model->data_count($where);
        $data = $this->model->data_list($where, '*', $sort_by, $page, $pageSize);
        return $this->success_return('success', [
            'total' => $total,
            'list' => $data,
            'el_table_column' => $this->el_table_column(),
            'search_fields' => $this->_searchField()
        ]);
    }

    public function get($args = []): array
    {
        $id = intval($args['id'] ?? 0);
        $data = $this->model->data_get(["role_id" => $id]);
        if (!$data) {
            return $this->error_return('数据不存在');
        }
        return $this->success_return('success', [
            'info' => $data
        ]);
    }


    public function set_status($args): array
    {
        $id = intval($args['id'] ?? 0);
        if (!$id) {
            return $this->error_return('参数错误');
        }
        $data = $this->model->data_get(["role_id" => $id], 'status');
        if (!$data) {
            return $this->error_return('数据不存在');
        }
        $res = (new Role())->data_update(["role_id" => $id], ['status' => $data['status'] == 1 ? -1 : 1]);
        if (!$res) {
            return $this->error_return('修改状态失败');
        }
        admin_log('修改状态', $args);
        return $this->success_return('保存成功');
    }

    public function del_data($args): array
    {
        $id = $args['id'] ?? [];
        if (!$id) {
            return $this->error_return('请选择数据');
        }
        $data = $this->model->data_get(['role_id' => $id], '*')?->toArray();
        if (!$data) {
            return $this->error_return('数据不存在');
        }
        $hasAdmin = (new Admin())->data_count(['role_id' => $id]);
        if ($hasAdmin) {
            return $this->error_return('该角色下有管理员，不能删除');
        }
        $res = $this->model->data_del(['role_id' => $id]);
        admin_log('删除角色数据', $data);
        return $this->success_return('删除成功');
    }

    public function list_options($args = []): array
    {
        $all = $this->model->data_list_nopage();
        if ($all) {
            foreach ($all as &$item) {
                $item['label'] = $item['role_name'];
                $item['value'] = $item['role_id'];
            }
        }
        return self::success_return('success', [
            'list' => $all,
        ]);
    }

    private function menu_list()
    {
        $all = (new AdminMenu())->data_list_nopage([
            //'hidden' => 0
            //'type' => 0
        ], 'id as menu_id,title as label,id as value,parent_id,type');
        if ($all) {
            $all = getTree($all, 'menu_id', 'parent_id');
        }
        return $all;
    }

    public function auths($args = []): array
    {
        $role_id = intval($args['id'] ?? 0);
        $modelAuths = new RoleAuths();
        $allIds = $modelAuths->data_list_nopage(['role_id' => $role_id], 'menu_id');
        return self::success_return('success', [
            'menu_ids' => $allIds ? array_column($allIds, 'menu_id') : [],
            'menu_list' => $this->menu_list(),
        ]);
    }

    public function auths_save($args): array
    {
        $role_id = intval($args['id'] ?? 0);
        $ids = $args['ids'] ?? [];
        if (!$role_id) {
            return self::error_return('参数错误');
        }
        $modelAuths = new RoleAuths();
        $modelAuths->data_del(['role_id' => $role_id]);
        if ($ids) {
            $data = [];
            foreach ($ids as $id) {
                $data[] = ['role_id' => $role_id, 'menu_id' => $id];
            }
            $modelAuths->saveAll($data);
        }
        admin_log('保存权限', $args);
        return self::success_return('success');
    }
}
